package ru.athena.runTool.blockTypes;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import ru.athena.runTool.ScriptParser;
import ru.athena.runTool.Model.CompositeNode;

public class Script extends ru.athena.runTool.blockTypes.ExecutableBlock {
	public static final String RUNTOOL_CURR_SCRIPT_DIR = "runTool.current.script.dir";
	private String fileNameFull_;

	@Override
	public void execute(Connection conn) throws Exception {
		for (CodeBlock i :  parseFile( fileNameFull_  )) {
			i.execute(conn);
		}
	}
	
	private static String extractScriptFullName(String rawName) {
		String fileName = rawName;
		if ( fileName.charAt(0) == '@') {
			if ( fileName.charAt(1) == '@') {
				fileName = fileName.substring(2);				
			}
			else {
				fileName = fileName.substring(1);
			}
		}
	
		int length = fileName.length();
		if ( fileName.charAt(length - 1) == ';') {
			fileName = fileName.substring(0, length - 1);
		}
		return fileName;
	}

	public Script(String path ) {
		this( new File( extractScriptFullName( path )), extractScriptFullName( path ) );
	}

	public Script(File file , String sourceFilePath ) {
		super("@" + file.getName());
		try {
			fileNameFull_ = sourceFilePath;
			// if it's full windows path ( ":" exists) - do not transform it
			if ( fileNameFull_.indexOf( ':') == -1 ) {
				String currentDir = System.getProperty(RUNTOOL_CURR_SCRIPT_DIR );
				// if gived path is not absolute (it's right for not first files) - 
				// current dir must be already set
				assert currentDir != null : "Current script dir is not set ";
				file = new File( currentDir + File.separator + fileNameFull_ );
			}
			fileNameFull_ = file.getCanonicalPath();
		} catch (IOException e) {
			setText( e.toString() );			
		}
	}
	
	public String getFullName() {
		return fileNameFull_;
	}
	/**
	 * 
	 * @return TreeNode, which contains all blocks, found in this script.
	 * 			Nested imported scripts will be a composite nodes.     
	 */
	@Override
	public CompositeNode toTreeNode() {
		// setting current directory
		String currentDir = System.getProperty(RUNTOOL_CURR_SCRIPT_DIR);
		if ( currentDir == null || currentDir.equals("")) {
			// "current dir" is "user.dir" property
			System.setProperty(RUNTOOL_CURR_SCRIPT_DIR, new File(fileNameFull_).getParent() );			
		}
		
		CompositeNode root = new CompositeNode(this);		
		for (CodeBlock	cb : parseFile( fileNameFull_ )) {
			root.add( cb.toTreeNode() );
		}
		return root;
	}

	/**
	 * @return List of code blocks, found in file 
	 */
	private List<CodeBlock> parseFile( String fileName ) {
		assert fileName != null : "Initialize file name first";
		ScriptParser	p = new ScriptParser();
		return p.parseFile( new File( fileName ) );
	}
	
	
}
